package com.study.lxy.springcloud.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.study.lxy.springcloud.common.entity.RequestLog;
import com.study.lxy.springcloud.common.utils.servlet.MyHttpServletResponseWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.*;

public class RequestLogUtil {
    private static final Logger logger = LoggerFactory.getLogger(RequestLog.class);
    public static RequestLog buildLog(ServletRequest request, MyHttpServletResponseWrapper wrapper){
        return buildLog(request,wrapper,null);
    }

    public static RequestLog buildLog(ServletRequest request,MyHttpServletResponseWrapper wrapper,String requestData){
        RequestLog log = new RequestLog();
        log.setRequestUrl(((HttpServletRequest)request).getRequestURL().toString());
        request.getContentType();
        if(requestData == null) {
            log.setRequestData(getRequestData((HttpServletRequest) request));
        } else {
            log.setRequestData(requestData);
        }
        log.setResponseData(wrapper.getResponseBody());
        try{
            JSONObject jo = JSON.parseObject(wrapper.getResponseBody());
            log.setReturnCode(jo.getString("errorCode"));
            log.setReturnMsg(jo.getString("errorMsg"));
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return log;
    }

    public static String getRequestData(HttpServletRequest request){
        try {
            logger.info("content type : {}", request.getContentType());
            if("application/json".equals(request.getContentType())){
                return getRequestPostStr(request);
            } else {
                return JSON.toJSONString(request.getParameterMap());
            }
        } catch(Exception ex){
            logger.error("getRequestData error.",ex);
        }
        return "";
    }

    /**
     * 描述:获取 post 请求的 byte[] 数组
     * <pre>
     * 举例：
     * </pre>
     * @param request
     * @return
     * @throws IOException
     */
    private static byte[] getRequestPostBytes(HttpServletRequest request)
            throws IOException {
        int contentLength = request.getContentLength();
        if(contentLength<0){
            return null;
        }

        byte buffer[] = new byte[contentLength];

        InputStream inputStream = request.getInputStream();
        for (int i = 0; i < contentLength;) {

            int readlen = inputStream.read(buffer, i,
                    contentLength - i);
            if (readlen == -1) {
                break;
            }
            i += readlen;
        }

        return buffer;
    }

    /**
     * 描述:获取 post 请求内容
     * <pre>
     * 举例：
     * </pre>
     * @param request
     * @return
     * @throws IOException
     */
    private static String getRequestPostStr(HttpServletRequest request)
            throws IOException {
        byte buffer[] = getRequestPostBytes(request);
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = "UTF-8";
        }
        return new String(buffer, charEncoding);
    }

    private static String getPostDataJson(HttpServletRequest request) throws IOException{
        logger.info("start to getPostDataJson");
        //BufferedReader br = request.getReader();
        BufferedReader br = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
        StringBuffer sb = new StringBuffer();
        String line = null;
        while((line = br.readLine()) != null){
            sb.append(line);
        }
        return sb.toString();
    }

}
